// pages/index/index.js
const { apiService } = require('../../utils/api')
const { formatPrice, getRelativeTime, getDifficultyText, getDifficultyStars, showError, showSuccess } = require('../../utils/util')

Page({
  data: {
    // 搜索相关
    searchKeyword: '',

    // 分类相关
    categories: [
      { id: 0, name: '全部', active: true },
      { id: 1, name: '刺绣', active: false },
      { id: 2, name: '编织', active: false },
      { id: 3, name: '手工饰品', active: false },
      { id: 4, name: '其他', active: false }
    ],

    // 手工品列表
    products: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10,

    // 统计数据
    stats: {
      totalProducts: 0,
      completedTasks: 0,
      totalEarnings: 0
    },

    // 轮播图
    banners: [
      {
        id: 1,
        image: '/images/banner1.jpg',
        title: '新手专享优惠',
        subtitle: '首次领取立减5元',
        link: '/pages/products/products'
      },
      {
        id: 2,
        image: '/images/banner2.jpg',
        title: '高额返现活动',
        subtitle: '完成任务最高返现20%',
        link: '/pages/tasks/tasks'
      },
      {
        id: 3,
        image: '/images/banner3.jpg',
        title: 'VIP特权升级',
        subtitle: '专属客服，优先派单',
        link: '/pages/profile/profile'
      }
    ],

    // 热门推荐
    hotProducts: [],

    // 快速入口
    quickActions: [
      {
        id: 1,
        icon: '/images/icons/handcraft.png',
        title: '领取任务',
        desc: '海量手工品任你选',
        path: '/pages/products/products'
      },
      {
        id: 2,
        icon: '/images/icons/task.png',
        title: '我的任务',
        desc: '查看进行中任务',
        path: '/pages/tasks/tasks'
      },
      {
        id: 3,
        icon: '/images/icons/wallet.png',
        title: '收益结算',
        desc: '查看收入明细',
        path: '/pages/settlements/settlements'
      },
      {
        id: 4,
        icon: '/images/icons/kefu.png',
        title: '在线客服',
        desc: '有问题随时问',
        path: '/pages/service/service'
      }
    ]
  },

  onLoad: function (options) {
    // 检查登录状态
    this.checkLoginStatus()

    // 加载首页数据
    this.loadHomeData()
  },

  onShow: function () {
    // 每次显示页面时刷新数据
    this.refreshData()
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus: function() {
    const app = getApp()
    // 先不强制跳转到登录页，让用户可以看到首页内容
    // 可以在用户需要操作时再检查登录状态
    console.log('当前登录状态:', app.isLoggedIn())
  },

  /**
   * 加载首页数据
   */
  loadHomeData: async function() {
    try {
      await Promise.all([
        this.loadBanners(),
        this.loadHotProducts(),
        this.loadProducts(true),
        this.loadUserStats()
      ])
    } catch (error) {
      console.error('加载首页数据失败:', error)
      // 如果API请求失败，设置默认数据，确保页面正常显示
      this.setDefaultData()
    }
  },

  /**
   * 加载轮播图数据
   */
  loadBanners: async function() {
    try {
      const result = await apiService.getActiveBanners()
      // 处理轮播图数据，确保格式正确
      const banners = result.map(banner => ({
        id: banner.id,
        image: banner.imageUrl,
        title: banner.title,
        subtitle: banner.subtitle || '',
        link: banner.link,
        linkType: banner.linkType
      }))
      this.setData({ banners })
    } catch (error) {
      console.error('加载轮播图失败:', error)
      // 保持默认轮播图数据
    }
  },

  /**
   * 设置默认数据
   */
  setDefaultData: function() {
    // 设置默认的手工品数据
    const defaultProducts = [
      {
        id: 1,
        name: '精美刺绣手帕',
        description: '手工刺绣，传统工艺',
        imageUrl: '/images/default-product.png',
        unitPrice: 15.50,
        difficultyLevel: 2,
        stockQuantity: 50,
        orderCount: 128
      },
      {
        id: 2,
        name: '手工编织围巾',
        description: '温暖舒适，多种颜色可选',
        imageUrl: '/images/default-product.png',
        unitPrice: 28.00,
        difficultyLevel: 1,
        stockQuantity: 30,
        orderCount: 89
      }
    ]

    this.setData({
      products: defaultProducts,
      hotProducts: defaultProducts.slice(0, 3)
    })
  },

  /**
   * 加载热门商品
   */
  loadHotProducts: async function() {
    try {
      const params = {
        page: 1,
        pageSize: 6, // 只显示6个热门商品
        status: 1, // 只显示上架的商品
        isHot: true, // 获取热门商品
        sortBy: 'orderCount', // 按订单数排序
        sortOrder: 'desc'
      }

      const result = await apiService.getProductsList(params)
      this.setData({
        hotProducts: result.list || []
      })
    } catch (error) {
      console.error('加载热门商品失败:', error)
      // 热门商品加载失败不影响整体使用
    }
  },

  /**
   * 加载用户统计数据
   */
  loadUserStats: async function() {
    const app = getApp()
    // 只有在已登录状态下才加载用户统计数据
    if (app.isLoggedIn()) {
      try {
        const stats = await apiService.getUserStats()
        this.setData({
          stats: {
            totalProducts: stats.totalProducts || 0,
            completedTasks: stats.completedTasks || 0,
            totalEarnings: stats.totalEarnings || 0
          }
        })
      } catch (error) {
        console.error('加载统计数据失败:', error)
        // 设置默认数据
        this.setData({
          stats: {
            totalProducts: 0,
            completedTasks: 0,
            totalEarnings: 0
          }
        })
      }
    } else {
      // 未登录状态下显示默认数据
      this.setData({
        stats: {
          totalProducts: 12,
          completedTasks: 0,
          totalEarnings: 0
        }
      })
    }
  },

  /**
   * 加载手工品列表
   */
  loadProducts: async function(refresh = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const page = refresh ? 1 : this.data.page
      const params = {
        page: page,
        pageSize: this.data.pageSize,
        status: 1, // 只显示上架的商品
        keyword: this.data.searchKeyword,
        categoryId: this.getActiveCategoryId()
      }

      const result = await apiService.getProductsList(params)

      const newProducts = result.list || []
      const products = refresh ? newProducts : [...this.data.products, ...newProducts]

      this.setData({
        products: products,
        page: refresh ? 2 : this.data.page + 1,
        hasMore: newProducts.length === this.data.pageSize,
        loading: false
      })

    } catch (error) {
      console.error('加载手工品列表失败:', error)
      this.setData({ loading: false })
      showError('加载失败，请重试')
    }
  },

  /**
   * 获取当前激活的分类ID
   */
  getActiveCategoryId: function() {
    const activeCategory = this.data.categories.find(cat => cat.active)
    return activeCategory ? activeCategory.id : 0
  },

  /**
   * 刷新数据
   */
  refreshData: function() {
    this.setData({
      products: [],
      page: 1,
      hasMore: true
    })
    this.loadHomeData()
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh: function() {
    this.refreshData()
    wx.stopPullDownRefresh()
  },

  /**
   * 上拉加载更多
   */
  onReachBottom: function() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadProducts()
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  /**
   * 搜索确认
   */
  onSearchConfirm: function() {
    this.refreshData()
  },

  /**
   * 清除搜索
   */
  onClearSearch: function() {
    this.setData({
      searchKeyword: ''
    })
    this.refreshData()
  },

  /**
   * 切换分类
   */
  onCategoryChange: function(e) {
    const categoryId = parseInt(e.currentTarget.dataset.id)

    const categories = this.data.categories.map(cat => ({
      ...cat,
      active: cat.id === categoryId
    }))

    this.setData({ categories })
    this.refreshData()
  },

  /**
   * 点击手工品卡片
   */
  onProductTap: function(e) {
    const productId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${productId}`
    })
  },

  /**
   * 立即领取
   */
  onClaimTask: function(e) {
    e.stopPropagation() // 阻止冒泡到父元素

    const productId = e.currentTarget.dataset.id
    const product = this.data.products.find(p => p.id === productId)

    if (!product) return

    // 检查库存
    if (product.stockQuantity <= 0) {
      showError('库存不足')
      return
    }

    // 检查登录状态
    const app = getApp()
    if (!app.isLoggedIn()) {
      // 未登录则跳转到登录页面
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }

    // 跳转到任务领取页面
    wx.navigateTo({
      url: `/pages/claim-task/claim-task?productId=${productId}`
    })
  },

  /**
   * 分享
   */
  onShareAppMessage: function() {
    return {
      title: '手工外发平台 - 赚取外快的好机会',
      path: '/pages/index/index',
      imageUrl: '/images/share-image.jpg'
    }
  },

  /**
   * 快速入口点击
   */
  onQuickActionTap: function(e) {
    const path = e.currentTarget.dataset.path
    if (path) {
      wx.navigateTo({
        url: path
      })
    }
  },

  /**
   * 轮播图点击
   */
  onBannerTap: function(e) {
    const { link, linkType } = e.currentTarget.dataset
    if (link) {
      if (linkType === 1) {
        // 内部页面
        if (link.startsWith('/pages/')) {
          wx.navigateTo({
            url: link
          })
        }
      } else if (linkType === 2) {
        // 外部链接，复制到剪贴板
        wx.setClipboardData({
          data: link,
          success: function() {
            wx.showToast({
              title: '链接已复制',
              icon: 'success'
            })
          }
        })
      }
    }
  },

  /**
   * 热门商品点击
   */
  onHotProductTap: function(e) {
    const productId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${productId}`
    })
  },

  /**
   * 查看更多热门商品
   */
  onViewMoreHot: function() {
    wx.switchTab({
      url: '/pages/products/products'
    })
  },

  /**
   * 分享
   */
  onShareAppMessage: function() {
    return {
      title: '手工外发平台 - 赚取外快的好机会',
      path: '/pages/index/index',
      imageUrl: '/images/share-image.jpg'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline: function() {
    return {
      title: '手工外发平台 - 赚取外快的好机会',
      imageUrl: '/images/share-image.jpg'
    }
  }
})
